package com.znf4.controller.login;

import javax.servlet.http.HttpSession;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.znf4.common.BaseController;
import com.znf4.constants.CommonConst;
import com.znf4.entity.ApiCommonResultVo;
import com.znf4.id.IdGenerator;
import com.znf4.user.info.entity.UserInfo;
import com.znf4.user.info.server.UserInfoServer;
import com.znf4.utils.RandomUtils;
import com.znf4.utils.SmsUtil;
import com.znf4.utils.StringUtil;



/**
 * 商户登录Controller
 */
@Controller
public class LoginController extends BaseController {
	
	private static final Log LOG = LogFactory.getLog(LoginController.class);
	


	
	@Autowired
	private UserInfoServer userInfoServer ;
	
	@Autowired
	private IdGenerator idGenerator ;
	
	
	
	
	/**
	 * 函数功能说明 ：绑定手机号
	 * 
	 * @参数： @return
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "/addUser", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public ApiCommonResultVo addUser(HttpSession session, String mobile, String code, String openId) throws Exception {

		try {
			String smsCode = (String) session.getAttribute(CommonConst.SMS_CODE);
			if (smsCode == null) {
				return new ApiCommonResultVo(-1, "验证码不存在", "");
			}
			if (!smsCode.equals(code)) {
				return new ApiCommonResultVo(-1, "验证码错误", "");
			}
			UserInfo userInfo = new UserInfo();
			userInfo.setUsername(mobile);
			userInfo.setOpen_id(openId);
			if (StringUtil.isEmpty(userInfoServer.queryOne(userInfo))) {
				LOG.info("新用户增加");
				userInfo.setId(idGenerator.getUserId());
				userInfoServer.addUserInfo(userInfo);
			} else {
				LOG.info("老用户从新绑定");
				userInfoServer.updateUserInfo(userInfo);
			}
		} catch (Exception e) {
			LOG.info("发送短信异常", e);
			return new ApiCommonResultVo(-1, "系统异常", "");
		}
		return new ApiCommonResultVo(0, "操作成功", "");
	}
	
	
	/**
	 * 函数功能说明 ：发送短信
	 * 
	 * @参数： @return
	 * @return String
	 * @throws
	 */
	@RequestMapping(value = "/sendSms", method = { RequestMethod.POST, RequestMethod.GET })
	@ResponseBody
	public ApiCommonResultVo sendSms(String mobile , HttpSession session) throws Exception {

		try {
			String code = RandomUtils.getRandomNum() + "";
			// 大鱼
			SmsUtil.sendCodeDyu(mobile, code);
			session.setAttribute(CommonConst.SMS_CODE, code);
		} catch (Exception e) {
			LOG.info("系统异常 :" + e.getMessage());
			return new ApiCommonResultVo(-1, "发送失败,请稍后再试", "");
		}
		return new ApiCommonResultVo(0, "发送成功", "");
	}
	
	

}
